(function () {
    var order = `<li class="order-list-item">
                    <div class="order-game">
                        <img class="order-game-img" data-original="{% data.game_img %}">
                        <div class="order-game-name ellipse">{% data.game_name %}</div>
                    </div>
                    <div class="order-consume">{% data.money %}</div>
                    <div class="order-time">{% data.add_time %}</div>
                    <div class="order-btn">{% data.pays %}</div>
                </li>`;
    var  game = `
    <li class="common-game-item">      
        <div class="common-game-avatar">        
            <img data-original="{% data.img %}">      
        </div>
        <div class="common-game-detail">
            <div class="common-game-info">
                <div class="common-game-name">
                    <div class="common-game-title ellipse">{% data.name %}</div>
                        {% if( data.is_android ){ %}
                            <span class="iconfont icon-anzhuo"></span>
                        {% } %}
                        {% if( data.is_ios ){ %}
                            <span class="iconfont icon-iOS"></span>
                        {% } %}
                </div>
               
                {% if ( data.cate_id ){ %}
                <!--游戏-->
                <div class="common-game-intro">
                    <div class="game-cate">{% data.cate_id %}</div>
                    <div>{% data.nums %}人关注</div>
                </div>
                    {% if ( data.tags ){ %}
                        <div  class="common-game-additional common-game-tags">
                            {% for(var i = 0; i < data.tags.length; i++ ) { %}
                                <span> {% data.tags[i] %} </span>
                            {% } %}
                        </div>  
                    {% } %}     
                               
                {% }else if( data.intro ){ %}
                <!--礼包-->
                <div class="common-game-intro">
                    <div class="game-intro-text  ellipse">礼包码：{% data.code %}</div>
                </div>
                     
                {% }else if( data.total ){ %} 
                <!-- 玩币卡 -->
                <div class="common-game-intro" style="color: #666">
                    有效期：{% data.start_time %} 至 {% data.end_time %}
                </div>
                <div  class="common-game-additional">
                    <div style="margin-right: 20px">
                        玩币卡总额：<span style="color: #FF4545;">{% data.total %}</span>元
                    </div>
                    <div style="margin-right: 20px">
                        卡内余额：<span style="color: #FF4545;">{% data.balance %}</span>元
                    </div>
                </div>
                {% } %}  
            </div>
            {% if ( data.cate_id ){ %}
                <a class="common-game-btn" href="/game/detail/{% data.id %}" target="_blank">打开</a>
            {% }else if( data.intro ){ %}
                <div class="common-game-btn copy-btn" data-clipboard-text="{% data.code %}">复制</div>
            {% } %}   
        </div>
    </li>
    `;

    var memberUrl = ['/member/ajax_h5','/member/ajax_libao','/member/ajax_card','/member/ajax_order'];


    var intervalTimers = {
        mobile:{
            ma: '#sendMa',
            mobile: '[name="mobile"]',
            code: '[name="code"]',
            url: '/member/send_ma',
            time: 60,
            clock: null
        },
        old_mobile:{
            ma: '#sendMa1',
            mobile: '[name="old_mobile"]',
            code: '[name="old_code"]',
            url: '/member/send_ma/forget',
            time: 60,
            clock: null
        },
        new_mobile:{
            ma: '#sendMa2',
            mobile:'[name="new_mobile"]',
            code: '[name="new_code"]',
            url: '/member/send_ma',
            time: 60,
            clock: null
        }
    };

    var layer = $('.common-info-layer').SUIModel({
        shade: '.common-layer-shade'
    });

    function main() {
        var pages = $('.page-wrapper');
        var memberRender = [];

        var renderHanler = {
            'receive_time': utils.getLocalTime.bind(utils),
            'start_time': utils.getLocalTime.bind(utils),
            'end_time': utils.getLocalTime.bind(utils),
            'cate_id': utils.setDataItem.bind(utils),
            'tags': utils.setDataItem.bind(utils),
            'add_time': utils.getLocalTime.bind(utils)
        };


        //礼包复制功能
        var clipboard = new Clipboard('.copy-btn');


        //首屏渲染
        $('.slide-tab').slideTab({
            //初始化slideTab
            initTabFn: function ( _self ) {
                //创建点击加载更多功能
                var tabBtns = _self.Nodes.$thumbItems;
                $.each( tabBtns, function ( index, item ) {
                    //创建渲染对象
                    memberRender[index] = $.fn.render({
                        template: index < 3 ? game : order,
                        handleFn: renderHanler,
                        method: 'replaceWith',
                        insertTarget: index < 3 ? $('.member-list')[index] : $('.order-list')[0],
                        renderFn: function ( tmpl, data ) {
                            var html = index < 3 ? '<ul class="member-list">' : '<ul class="order-list">';
                            $.each( data, function ( index, item ) {
                                html += utils.parseTmpl( tmpl , item );
                            });
                            html += '</ul>';
                            return html;
                        },
                        afterRender: function () {
                            var me = this;
                            me.opts.insertTarget =  index < 3 ? $('.member-list')[index] : $('.order-list')[0];
                        }
                    });

                    //创建分页对象
                    $(pages[index]).pagination({
                        viewRender: {
                            //获取数据后自定义的渲染函数
                            render: function (data) {
                                var me = this;
                                memberRender[index].reRender( data, me.currentPage );
                            }
                        },
                        allPage: 1,              //默认总页数
                        showPageLength: 5,       //最多显示的页码个数
                        pageListCount: 10,       //当前列表显示个数

                        //获取首屏数据
                        initPagination: function (next) {
                            var me = this;
                            loadListData(memberUrl[index], 1, function (data) {
                                me.listData = data['info_list'];
                                me.opts.allPage = data.all_page;
                                next();
                            });
                        },

                        //跳转前获取数据
                        beforeJump: function(next){
                            var me = this;
                            loadListData(memberUrl[index], me.currentPage, function (data) {
                                me.listData = data['info_list'];
                                next();
                            });
                        },

                        //跳转后重新图片懒加载
                        afterRender: function () {
                            $("img").lazyload({
                                effect: "fadeIn",
                                effectspeed: 1500
                            });
                        }
                    });
                });
            },
            afterChangeFn: function ( _self ) {
                $("img").lazyload({
                    effect: "fadeIn",
                    effectspeed: 1500
                });
            }
        });

        initInput();

        sendMa('mobile');
        sendMa('old_mobile');
        sendMa('new_mobile');

        //绑定open
        bindControlPanelBtn();

        //提交表单
        submitInputInfo('.submit-btn', {
            bindMobileForm: '/member/ajax_bind_mobile',
            alterMobileForm: '/member/ajax_replace_mobile',
            alterPwForm: '/member/ajax_edit_password'
        });
    }

    //分页加载表单列表
    function loadListData(url, page, resolve) {
        $.ajax({
            type: "GET",
            url: url,
            data: {
                page : page,
                limit : 10
            },
            dataType:"json",
            success: function ( res ) {
                if( res.ret === 0 ){
                    resolve(res.data);
                }
            }
        });
    }

    function initInput() {
        var inputs = [{
            node: '[name="mobile"]',
            verifyFn: function ( val ) {
                return verifyInputFn( /^\d{11}$/g, val, '请输入正确的手机号')
            }
        },{
            node: '[name="new_mobile"]',
            verifyFn: function ( val ) {
                return verifyInputFn( /^\d{11}$/g, val, '请输入正确的手机号')
            }
        },{
            node: '[name="code"]',
            verifyFn: ''
        },{
            node: '[name="password"]',
            verifyFn: function ( val ) {
                return verifyInputFn( /^.{6,14}$/g, val, '请输入6到14位的密码')
            }
        },{
            node: '[name="new_password"]',
            verifyFn: function ( val ) {
                return verifyInputFn( /^.{6,14}$/g, val, '请输入6到14位的密码')
            }
        },{
            node: '#confirmNewPassword',
            verifyFn: function ( val ) {
                var newPw = $('[name="new_password"]').val().trim(),
                    text = '';
                if(newPw !== val){
                    text = '两次输入的密码不相同';
                }
                return text;
            }
        }];


        $.each( inputs, function ( index,item ) {
            var $input = $( item.node );
            $input.data('verifyFn', item.verifyFn);
            $input.on({
                focus: function (e) {
                    e = e || event;
                    //重置
                    $input.val('');
                    setErrorText($input, '', 'remove');
                }
            })
        });
    }

    //工厂函数,返回表单验证结果
    function verifyInputFn( patt, val, errText ) {
        var text = '';
        if( !patt.test(val) ){
            text = errText;
        }
        return text;
    }

    //绑定打开
    function bindControlPanelBtn() {
        var $selector = $('.member-btn'),
            panelId,
            $panel;
        if( !$selector ){
            return false;
        }else{
            $selector.on('click',function (e) {
                e = e || event;
                if( !$( e.target ).attr( 'data-fold-show' )){
                    return false;
                }else{
                    panelId = $( e.target ).attr('data-fold-show');
                    $panel = $('[data-fold-panel=' + panelId + ']');
                    $('.icon-cha').off('click').on('click', function () {
                        $panel.hide();
                        layer.close();

                    });
                    layer.open();
                    $panel.show();
                    for(let name in intervalTimers){
                        reset(intervalTimers[name]);
                    }
                }
            })
        }
    }

    //重置验证码
    function reset(timer) {
        timer.time = 60;
        $(timer.ma).removeClass('member-setting-btn-disabled').text('发送验证码');
        clearInterval(timer.clock);
        timer.clock = null;
    }

    //发送验证码
    function sendMa(name) {
        var timer = intervalTimers[name];
        var $selector = $(timer.ma);
        $selector.on('click',function () {
            if(timer.time >= 60){
                var $mobile = $(timer.mobile), value;
                if( verifyInputInfo( $mobile ) ){
                    value = $mobile.val().trim();
                    $.ajax({
                        type: "POST",
                        url: timer.url,
                        data: {
                            mobile: value
                        },
                        dataType:"json",
                        success: function (res) {
                            if( res.ret === 0 ){
                            }else{
                                alert( res.msg );
                            }
                        }
                    });

                    timer.clock = setInterval(function () {
                        $selector.text( timer.time-- + '秒后重新发送');
                        if(timer.time < 0 ){
                            reset(timer);
                        }
                    },1000);
                    $(this).addClass('member-setting-btn-disabled');
                }
            }
        });
    }

    //提交表单
    function submitInputInfo( selector, urls ) {
        $(selector).on('click',function (e) {
            e = e || event;
            var id = $( e.target ).attr('data-fold-submit'),            //获取当前的表单名称
                inputs = $('[data-fold-panel=' + id + ']').find('input'),
                data = {},
                errFlags = [];

                //获取表单数据
                $.each( inputs, function ( index, item ) {
                    var $input = $(item),
                        key = $input.attr('name'),
                        val = $input.val().trim(),
                        errFlag = verifyInputInfo( $input, $input.data('verifyFn'));
                    if( !errFlag ){
                        errFlags.push( errFlag );
                    }
                    if( key ){
                        data[key] = val;
                    }
                });

                if( !errFlags.length ){
                    //提交
                    submitForm(data, urls[id]);
                }
            })
    }

    //绑定手机 || 修改密码
    function submitForm( data, url ) {
        $.ajax({
            type: "POST",
            url: url,
            data: data,
            dataType:"json",
            success: function (res) {
                if( res.ret === 0 ){
                    window.location.href = '/member/';
                }else{
                    alert( res.msg );
                }
            }
        });
    }
    
    //表单验证
    function verifyInputInfo( selector, call ) {
        var $selector = selector instanceof jQuery ? selector : $(selector),
            fn = call || '',
            value,
            text;
        if( !$selector ){
            return false;
        }else{
            value = $selector.val().trim();
            if( !value ){
                //如果存在为空的值
                setErrorText($selector, '输入不能为空', 'add');
                return false;
            }else if( fn && typeof fn === 'function' && fn( value ) ){
                setErrorText( $selector, fn( value ) , 'add');
                return false;
            }else{
                return true;
            }
        }
    }

    //错误提示
    function setErrorText( $selector, text, type ) {
        var $father = $selector.parent('[data-input-error]');

        $father[type + 'Class']('panel-row-error');
        $father.attr('data-input-error', text);
    }

    main();
})();
